#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#========================================================================
#   FileName: loginOA.py
#     Author: linh
#      Email: linh@ecallcen.com
# LastChange: 2012-05-13 15:21:16
#========================================================================
import urllib2,urllib,cookielib
import sys,urllib2,urllib,cookielib
import datetime
import os,sys
import ConfigParser
import logging
import logging.handlers
from sgmllib import SGMLParser
from ServiceUtil import ParamUtil
class AnalyseDutyHtml(SGMLParser):
    def __init__(self):
      SGMLParser.__init__(self)
      self.isTd=False
      self.isbr=False
      self.onDutyList=[]
      self.dayDutyList=[]
      self.onDutyList.append(self.dayDutyList)
    def start_tr(self,attrs):
        for k,v in attrs:
            if k=='class' and v=='TableData' and len(self.dayDutyList)>0:
                self.dayDutyList=[]
                self.onDutyList.append(self.dayDutyList)
    def start_td(self,attrs):
        self.isTd=True
    def start_br(self,attrs):
        self.isbr=True
    #def end_td(self,attrs):
        #if self.isTableData: 
            #self.isOnDutyData=False
    def handle_data(self, text):
        if self.isTd==True:
            if text.strip()<>'':self.dayDutyList.append(text)
            self.isTd=False

class Login():
    def __init__(self,user,password):
        self.userName=user
        self.password=password
        self.url='http://218.66.13.70:9099'
        try:
            cookie=cookielib.CookieJar()
            cookieProc=urllib2.HTTPCookieProcessor(cookie)
        except:
            raise
        else:
            opener=urllib2.build_opener(cookieProc)
            urllib2.install_opener(opener)       

    def getOndutyHtml(self,strBeginTime,strEndTime):

        postData={ 'DATE1':strBeginTime, 'DATE2':strEndTime }
        req=urllib2.Request(
                            self.url+'/general/attendance/personal/report/search.php',
                            urllib.urlencode(postData)            
                            )
        queryHtmlStr=urllib2.urlopen(req).read()
        return queryHtmlStr
    def login(self):
        postdata={
                  'UNAME':self.userName,
                  'PASSWORD':self.password
                  }
        req=urllib2.Request(
                            self.url+'/logincheck.php',
                            urllib.urlencode(postdata)            
                            )
        
        loginHtmlStr=urllib2.urlopen(req).read()
        #print loginHtmlStr
        #strBeginTime='2012-08-01'
        #strEndTime='2012-08-03'
        #postData={ 'DATE1':strBeginTime, 'DATE2':strEndTime }
        #req=urllib2.Request(
                            #self.url+'/general/attendance/personal/report/search.php',
                            #urllib.urlencode(postData)            
                            #)
        #queryHtmlStr=urllib2.urlopen(req).read()
        if(loginHtmlStr.find('goto_oa')>0):return True
        else: return False
        #ondutyObject.feed(queryHtmlStr)
        #print ondutyObject.ondutyObjectList        

def convertGBKToUTF8(unicodeMap):
    for key in unicodeMap.keys():
        if isinstance(unicodeMap[key],str):#遇到中文关键字，要把unicode类型转换为str类型.
            unicodeMap[key]=unicodeMap[key].decode('GBK').encode('UTF-8')
def analyiseOnduty(htmlList):
    """分析上班的数据"""
    tempMap={}
    for dutyList in htmlList:
        if len(dutyList)>=3:
            dutyDay=dutyList[0].split()[0]
            startDutyTime=dutyList[1].split()[0]
            endDutyTime=dutyList[2].split()[0]
            log.info('date:%s,startDuty:%s,endDuty:%s',dutyDay,startDutyTime,endDutyTime)
            tempMap[dutyDay]={'dutyDay':dutyDay,'startDutyTime':startDutyTime,'endDutyTime':endDutyTime,
                    'dutyDayStr':dutyList[0],'startDutyTimeStr':startDutyTime,'endDutyTimeStr':endDutyTime}
            convertGBKToUTF8(tempMap[dutyDay])
    return tempMap
def sendToSM(tempMap,servNbr):
    URL = 'http://218.85.155.18/iservuc/ServiceGate/SimpleXMLGate'
    smList=[]
    for key,ondutyMap in tempMap.items():
        if(ondutyMap['startDutyTime']=='未登记' or ondutyMap['endDutyTime']=='未登记'):
            smList.append(key+':')
            if(ondutyMap['startDutyTime']=='未登记'):
                smList.append('上班未登记')
            if(ondutyMap['endDutyTime']=='未登记'):
                smList.append('下班未登记')
            smList.append(';')
    if len(smList)>0:
        smContent='10000号维护小组友情提示:'+''.join(smList)
        smContent=smContent.decode('UTF-8').encode('GBK')
        log.info('发送短信:电话号码:%s,短信内容:%s',servNbr,smContent)
        paramList=[servNbr,smContent,'ECCOA','0','','5910','0591']
        paramUtil=ParamUtil()
        outputParam=paramUtil.invoke("TccsSmInsertFuncs",paramList,URL)

def readConfig(configDataMap):
    """
     从getIvrLog.ini中获取配置信息
     configDataMap必须是dict类型.
    """
    config=ConfigParser.ConfigParser()
    fileObject=open(config_dir+'loginOA.ini')
    config.readfp(fileObject)
    for section in config.sections():
        configData={}
        for option in config.options(section): configData[option]=config.get(section,option)
        configDataMap[section]=configData

if __name__ == '__main__':
    tempPath=os.path.split(sys.argv[0])#取文件名的路径。
    if tempPath[0]=='':#文件名采用绝对路径，而是采用相对路径时，取工作目录下的路径
        config_dir=os.getcwd()+os.sep
    else:
        config_dir=tempPath[0]+os.sep
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    h1 = logging.handlers.RotatingFileHandler(config_dir+'loginOA.log',maxBytes=2097152,backupCount=5)
    h1.setLevel(logging.INFO)
    f=logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    h1.setFormatter(f)
    log.addHandler(h1)
    configDataMap={}
    readConfig(configDataMap)
    currDate=datetime.datetime.today()
    yestoday=currDate-datetime.timedelta(days=1)
    if yestoday.isoweekday() in [4,6,7]:
        log.info('属于周末，跳过不告警')
    else:
        strBeginTime=yestoday.strftime('%Y-%m-%d')
        currDate=currDate+datetime.timedelta(days=1)
        strEndTime=currDate.strftime('%Y-%m-%d')
        for key,userInfoMap in configDataMap.items():
            log.info('username:%s,password:%s',userInfoMap['user'],userInfoMap['password'])
            tempLogin=Login(userInfoMap['user'],userInfoMap['password'])
            bLogin=tempLogin.login()
            log.info('user:%s  loginOA result is:%s',key,str(bLogin))
            if bLogin:
               log.info('user:%s  startBeginTime:%s,endBeginTime:%s',key,strBeginTime,strEndTime)
               dutyHtml=tempLogin.getOndutyHtml(strBeginTime,strEndTime)
               analyseDutyHtml=AnalyseDutyHtml()
               analyseDutyHtml.feed(dutyHtml)
               tempMap=analyiseOnduty(analyseDutyHtml.onDutyList)
               sendToSM(tempMap,userInfoMap['mobile'])
    h1.close()
